import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Select, Button, Table, Input, Modal } from "antd";
import dayjs from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat";
import { PlusOutlined, RedoOutlined, SearchOutlined } from "@ant-design/icons";
import { text_check, post_axios, fenToyuan } from "../../utils";

export default function MoneyAgree(props) {
  dayjs.extend(customParseFormat);
  const [tableHeight, setTableHeight] = useState(0);
  const { actions, setSpinning } = props;
  let { menu_action, user_power_lang, username, user_grade } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  // 国内国外判断
  const session_company = sessionStorage.getItem("company");
  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";

  const [log_list, setLog_list] = useState([]);
  const [page, setPage] = useState(1);
  const [rows, setRows] = useState(20);
  const [total, setTotal] = useState(0);

  const getData = async (newPage, newRows) => {
    let upMsg = {
      pageNum: newPage ? newPage : page,
      pageSize: newRows ? newRows : rows,
      status: 0,
      request_type: "findwithdrawal",
    };
    setSpinning(true);
    let res = await post_axios("union_pay", "union_pay", upMsg);
    setSpinning(false);
    if (!res) return;
    setLog_list(res.data.BusinessUser);
    setTotal(res.data.Total);
  };
  const columns = [
    {
      title: "公司名称",
      dataIndex: "companyName",
      align: "center",
    },
    {
      title: "银行卡属性",
      align: "center",
      render: (_, record) => (
        <>
          {record.bankCardPro == 0 ? (
            <span>个人银行卡</span>
          ) : (
            <span>企业对公账户</span>
          )}
        </>
      ),
    },
    {
      title: "提现金额(元)",
      dataIndex: "amount",
      align: "center",
    },
    {
      title: "提现状态",
      align: "center",
      render: (_, record) => (
        <>
          {record.status === 0 ? (
            <span>待审核</span>
          ) : record.status === 1 ? (
            <span>提现失败</span>
          ) : (
            <span>提现成功</span>
          )}
        </>
      ),
    },
    {
      title: "提交签订时间",
      dataIndex: "time",
      align: "center",
    },
    {
      title: "提现审批",
      align: "center",
      render: (_, record) => (
        <>
          <Button
            type="primary"
            onClick={() => money_pass(record)}
            size="small"
          >
            通过
          </Button>
          <Button
            type="primary"
            danger
            onClick={() => money_reject(record)}
            size="small"
            style={{ marginLeft: "10px" }}
          >
            驳回
          </Button>
        </>
      ),
    },
  ];
  // 分页器
  const pageOnChange = async (page, pageSize) => {
    setPage(page);
    setRows(pageSize);
    getData(page, pageSize);
  };

  const search_data = () => {
    setPage(1);
    getData(1);
  };

  // 查询余额
  const [acount_balance, setAacount_balance] = useState("0");
  const query_acount_balance = async () => {
    let upMsg = {
      request_type: "queryWithdrawalAmount",
      bizUserId: username,
    };
    setSpinning(true);
    let res = await post_axios("union_pay", "union_pay", upMsg);
    setSpinning(false);
    if (!res) return;
    let balance = `${Math.round(res.data.balance)}`;
    setAacount_balance(fenToyuan(balance));
  };

  const money_pass = async (value) => {
    let upMsg = {
      request_type: "withdrawal",
      bizUserId: value.bizUserId,
      amount: value.amount,
      Id: value.id,
    };
    let res = await post_axios("union_pay", "union_pay", upMsg);
    getData();
    query_acount_balance();
  };
  const money_reject = async (value) => {
    let upMsg = {
      request_type: "updateWithdrawal",
      bizUserId: value.bizUserId,
      Id: value.id,
    };
    let res = await post_axios("union_pay", "union_pay", upMsg);
    getData();
    query_acount_balance();
  };

  const [add_submit_reflect_show, setAdd_submit_reflect_show] = useState(false);
  // 查询可提现的余额
  const [withdrawal_balance, setWithdrawal_balance] = useState("");
  const query_Withdrawal_balance = async (bizUserId) => {
    let upMsg = {
      request_type: "balance",
      bizUserId,
    };
    let res = await post_axios("union_pay", "union_pay", upMsg);
    if (!res) return;
    let balance = `${Math.round(res.data.allAmount)}`;
    setWithdrawal_balance(fenToyuan(balance));
    let newObj = JSON.parse(JSON.stringify(submit_obj));
    newObj.bankCardNo = res.data.accountNo;
    newObj.amount = 0;
    newObj.mch = bizUserId;
    setSubmit_obj(newObj);
  };
  // 查询商户列表
  const [mch_list, setMch_list] = useState([]);
  const query_mch_list = async () => {
    let upMsg = {
      request_type: "findPage",
      pageNum: 1,
      pageSize: 1000,
      bizUserId: username,
    };
    let res = await post_axios("union_pay", "union_pay", upMsg);
    if (!res) return;
    console.log(res.data.BusinessUser);
    setMch_list(res.data.BusinessUser);
  };

  const [submit_obj, setSubmit_obj] = useState({
    amount: 0,
    mch: "",
    bankCardNo: "",
    bankCardPro: "1",
  });

  const submit_reflect_onChange = (value, key) => {
    if (key === "mch") {
      query_Withdrawal_balance(value);
    } else {
      let newObj = JSON.parse(JSON.stringify(submit_obj));
      newObj[key] = value;
      setSubmit_obj(newObj);
    }
  };

  const submit_reflect = async () => {
    setSubmit_obj({
      amount: 0,
      mch: "",
      bankCardNo: "",
      bankCardPro: "1",
    });
    setWithdrawal_balance("");
    await query_mch_list();
    setAdd_submit_reflect_show(true);
  };
  const add_submit_reflect_confirm = async () => {
    let { mch, ...others } = submit_obj;
    let upMsg = Object.assign(
      {
        request_type: "withdrawal",
        bizUserId: mch,
      },
      others
    );
    let res = await post_axios("union_pay", "union_pay", upMsg);
    if (!res) return;
    setAdd_submit_reflect_show(false);
    getData();
    query_acount_balance();
  };

  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabBoxHeight =
        document.getElementsByClassName("money_agree")[0].scrollHeight;
      const tableHeight = tabBoxHeight - 96 - 70;
      setTableHeight(tableHeight);
    });
    query_acount_balance();
  }, []);
  return (
    <>
      <div className="money_agree modules">
        <div className="screen_ipt">
          <div className="ipt_box">
            <div
              className="ipt_box_title"
              style={{
                color: "blue",
                fontSize: "18px",
                marginRight: "20px",
              }}
            >
              备付金:{acount_balance}元
            </div>
            <Button
              shape="circle"
              icon={<RedoOutlined />}
              onClick={query_acount_balance}
            />
          </div>
        </div>
        <div className="screen_btn">
          <div className="btn_box">
            <Button
              size="small"
              type="text"
              icon={<PlusOutlined style={{ color: "#1677FF" }} />}
              onClick={submit_reflect}
            >
              提现
            </Button>
            {/* 查询 */}
            <Button
              size="small"
              type="text"
              icon={<SearchOutlined style={{ color: "#1677FF" }} />}
              onClick={search_data}
            >
              {text_check(user_power_lang["m_query"])}
            </Button>
          </div>
        </div>
        <div className="table_box">
          <div className="page-table">
            <Table
              dataSource={log_list}
              size="small"
              bordered
              columns={columns}
              rowKey="id"
              virtual
              scroll={{
                y: tableHeight,
              }}
              pagination={{
                defaultCurrent: page,
                defaultPageSize: rows,
                size: "small",
                current: page,
                total: total,
                responsive: true,
                showTotal: (total) =>
                  text_check({
                    msg_cn: `共 ${total} 条`,
                    msg_en: `Total ${total} items`,
                  }),
                onChange: pageOnChange,
              }}
            />
          </div>
        </div>
      </div>
      <Modal
        title="提现"
        open={add_submit_reflect_show}
        onOk={add_submit_reflect_confirm}
        onCancel={() => setAdd_submit_reflect_show(false)}
        classNames={{ body: "edit_dialog_body" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">签约商户</div>
          <Select
            placeholder=" "
            options={mch_list}
            fieldNames={{
              label: "signAcctName",
              value: "bizUserId",
            }}
            value={submit_obj.mch}
            onChange={(value) => submit_reflect_onChange(value, "mch")}
          />
        </div>

        <p
          style={{
            width: "100%",
            color: "red",
            margin: "-10px 0",
            textAlign: "center",
          }}
        >
          * 请先选择商户
        </p>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">绑定账号</div>
          <Input placeholder=" " value={submit_obj.bankCardNo} readOnly />
        </div>

        <p
          style={{
            width: "100%",
            color: "red",
            margin: "-10px 0",
            textAlign: "center",
          }}
        >
          可用余额 {withdrawal_balance} 元
        </p>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">签约商户</div>
          <Input
            placeholder=" "
            value={submit_obj.amount}
            onChange={(e) => submit_reflect_onChange(e.target.value, "amount")}
          />
        </div>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">账户属性</div>
          <Select
            placeholder=" "
            options={[
              {
                label: "个人银行卡",
                value: "0",
              },
              {
                label: "企业对公账户",
                value: "1",
              },
            ]}
            value={submit_obj.bankCardPro}
            onChange={(value) => submit_reflect_onChange(value, "bankCardPro")}
          />
        </div>
      </Modal>
    </>
  );
}
